package com.mystore.service.impl;

import com.mystore.dao.UserDao;
import com.mystore.dao.impl.UserDaoImpl;
import com.mystore.entity.User;
import com.mystore.exception.UserException;
import com.mystore.service.UserService;
import com.mystore.util.DBUtil;
import com.mystore.util.PassUtil;
import com.mystore.vo.UserVO;

import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService{


    /**
     * 新增用户
     * @param userVO
     * @return
     */
    @Override
    public Boolean addUser(UserVO userVO) throws UserException {
        Connection connection = DBUtil.getConntion();
        UserDao userDao = new UserDaoImpl();
        Object object = userDao.findByUsername(userVO.getUsername(),connection);
        try {
            if(object==null){
            userVO.setPassword(PassUtil.EncoderByMd5(userVO.getPassword()));
                return userDao.save(userVO, connection);
            }else{
                throw new UserException("当前用户已存在");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }finally {
            DBUtil.closeConnection(connection);
        }
    }

    /**
     * 用户登录
     * @param userVO
     * @return
     * @throws UserException
     */
    public User isLogin(UserVO userVO) throws UserException {
        Connection connection = DBUtil.getConntion();
        UserDao userDao = new UserDaoImpl();
        Object obj = userDao.findByUsername(userVO.getUsername(),connection);
        if(obj ==null){
            throw new UserException();
        }else{
           User user = (User) obj;
            String pass = user.getPassword();
            if(PassUtil.checkPass(user.getPassword(),userVO.getPassword())){
                return user;
            }
            return null;
        }
    }


}
